// subPackages/packageA/shesu/components/caseStatus/caseStatus.ts
import * as echarts from '../ec-canvas/echarts';
import { getSxYearCountListApi, getSxStatStatusListAPI } from "../../../api/shesu"
let caseData = []
function setOption(chart) {
  var option = {
    tooltip: {
      show: false,
      trigger: "item",
      backgroundColor: "rgba(0,0,0,0.7)",
      borderWidth: 0,
      textStyle: {
        color: "#fff",
        fontWeight: "normal"
      }
    },
    legend: {
      orient: "vertical",
      right: "10",
      top: "40%",
      textStyle: {
        fontSize: 14
      },
      itemWidth: 10, // 图例标记的宽度
      itemHeight: 10, // 图例标记的高度
      formatter: function (name) {
        const data = option.series[0].data
        const total = data.reduce((a, b) => {
          let num = b.value
          if (num || num == 0) {
            num = Number(b.value)
          }
          return a + num
        }, 0)
        const target = data.find((item) => item.name === name)
        const percentage = ((target.value / total) * 100).toFixed(2).replace(/\.00$/, "") + "%"
        return `{a| ${name}}` + " " + "{a|" + target.value + "}" + "  " + "{a|" + percentage + "}"
      },
      textStyle: {
        rich: {
          a: {
            fontSize: 14,
            color: "#1D2129",
            align: "right"
          }
        }
      }
    },
    color: ["#4458FE", "#D9E5FE"],
    series: [
      {
        name: "",
        type: "pie",
        radius: ["40%", "70%"],
        center: ["30%", "50%"],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: "center"
        },
        labelLine: {
          show: false
        },
        data: caseData
        // data: [
        //   { value: 1048, name: '已结案' },
        //   { value: 735, name: '未结案' }
        // ]
      }
    ]
  }
  chart.setOption(option);

}

Component({
  options: {
    styleIsolation: "apply-shared"
  },
  /**
   * 组件的属性列表
   */
  properties: {
    debtorId: {
      type: String,
      value: ""
    },
    businessType: {
      type: String,
      value: "1"
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    dateVisible: false,
    dateValue: [],
    dateText: '请选择年份',
    years: [],
    ec: {
      lazyLoad: true
    },
    emptyFlag: false
  },
  lifetimes: {
    attached: function () {
      this.ecComponent = this.selectComponent('#mychart-dom-case-status')
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    init() {
      this.ecComponent.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        setOption(chart);

        // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
        this.chart = chart;

        this.setData({
          isLoaded: true
        });
        return chart;
      });
    },
    getChartData() {
      getSxStatStatusListAPI({ id: this.data.debtorId, yearInfo: this.data.dateValue[0] || "", businessType: this.data.businessType }).then(
        (res) => {
          caseData = res.content || []
          if (caseData.length == 0) {
            this.setData({
              emptyFlag: true
            })
            return
          }
          this.init()
        }
      )
    },
    // 获取年份统计
    getSxYearCount() {
      getSxYearCountListApi({ id: this.data.debtorId, businessType: this.data.businessType }).then((res) => {
        this.data.years = res.content.map(item => {
          item.label = `${item.name}年(${item.value})`
          item.value = item.name
          return item
        })
        this.setData({
          years: this.data.years
        })
      })
    },
    onSeasonPicker() {
      this.setData({ dateVisible: true });
    },
    onPickerChange(e) {
      const { key } = e.currentTarget.dataset;
      const { value, label } = e.detail;
      console.log('picker change:', e.detail);
      this.setData({
        [`${key}Visible`]: false,
        [`${key}Value`]: value,
        [`${key}Text`]: label.join(' '),
      });
      this.getChartData()
    },
    onPickerCancel(e) {
      const { key } = e.currentTarget.dataset;
      this.setData({
        [`${key}Visible`]: false,
      });
    },
  },
  observers: {
    'debtorId': function () {
      if (this.data.debtorId) {
        this.getSxYearCount()
        this.getChartData()
      }
    }
  },
})